package com.sky.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.sky.result.Result;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class OssUploadService {
    public Result<String> uploadFile(MultipartFile multipartFile){
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAI5t6EFtbJ3dncANNC2DGN";
        String accessKeySecretKey = "qnk9xB9x8kuBU0bwVbYNTF19ZPwNEQ";
        String bucketName = "sky-pojo";
        OSS ossClient = null;
        try {
           ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecretKey);
            if(!ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }

            //生成文件信息
            InputStream inputStream = multipartFile.getInputStream();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = dateFormat.format(new Date());
            String realFileName = multipartFile.getOriginalFilename();
            String imgSuffix = realFileName.substring(realFileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString() + imgSuffix;
            String fileUrl = datePath + "/" + newFileName;
            ossClient.putObject(bucketName,fileUrl,inputStream);
            return Result.success("https://"+ bucketName+"."+endpoint+"/"+fileUrl);
        } catch (Exception oe) {
            oe.printStackTrace();
            return Result.error("上传错误!");
        }  finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }
}
